/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2025-02-05
 * Time: 19:42
 */
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ResourceMonitoringExample {

    // 这里进行模拟任务
    static class Task implements Runnable {
        @Override
        public void run() {
            try {
                // 模拟耗时操作
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        int threadCount = 10; // 初始线程数量
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);

        // 记录开始时间
        long startTime = System.currentTimeMillis();

        // 提交任务
        for (int i = 0; i < 20; i++) {
            executor.submit(new Task());
        }

        // 关闭线程池
        executor.shutdown();
        while (!executor.isTerminated()) {
            // 监测资源使用状态
            monitorResources();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        // 记录结束时间
        long endTime = System.currentTimeMillis();
        long executionTime = endTime - startTime;
        System.out.printf("程序执行时间: %d 毫秒%n", executionTime);
    }

    // 监测资源使用状态
    private static void monitorResources() {
        // 监测 CPU 使用情况
        OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
        if (osBean instanceof com.sun.management.OperatingSystemMXBean) {
            com.sun.management.OperatingSystemMXBean sunOsBean = (com.sun.management.OperatingSystemMXBean) osBean;
            double cpuLoad = sunOsBean.getSystemCpuLoad();
            if (cpuLoad >= 0) {
                System.out.printf("当前系统 CPU 使用率: %.2f%%%n", cpuLoad * 100);
            }
        }

        // 监测线程数量
        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        int threadCount = threadBean.getThreadCount();
        System.out.printf("当前活动线程数量: %d%n", threadCount);
    }
}
